package pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @author khaiLoon
 * @date 2018/11/16
 **/
public class PDF {

    public static void main(String[] args) throws Exception {
        PDF.fillTemplate("", "", null);
    }

    public static void fillTemplate(String templatePath, String newPDFPath, List<String> li) throws Exception {
        FileOutputStream out = new FileOutputStream("/work/public/bold/early/src/main/resources/ok.pdf");// 输出流
        PdfReader reader = new PdfReader("/work/public/bold/early/src/main/resources/my.pdf");// 读取pdf模板
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        PdfStamper stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        String[] str = {"赵日天", "李四", "123456789", "111222333", "工商银行", "招商银行", "100.00", "壹佰圆整", "购买李四公司定金", "2018-01-01", "汇兑转出", "123000", "2018-01-01", "网银第1次打印", "000123"};
        int i = 0;
        java.util.Iterator<String> it = form.getFields().keySet().iterator();
        while (it.hasNext()) {
            String name = it.next();
            String value = String.valueOf(i++);
//            String value = li.get(i++);
            System.out.println(name + " : " + value);
            form.setField(name, value);
        }
        stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
        stamper.close();

        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
        copy.addPage(importPage);
        doc.close();
        reader.close();
        out.close();
    }
}
